package com.yumeng.common.runtime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @author wxd
 * @date 2024/5/28 下午3:10
 */
@Component
public class SpringPropAdapter {

    private final ServerProperties serverProperties;
    private final WebMvcProperties webMvcProperties;
    private final ApplicationContext applicationContext;//上下文环境


    private static SpringPropAdapter springPropAdapter;

    @Autowired
    public SpringPropAdapter(ServerProperties serverProperties, WebMvcProperties webMvcProperties, ApplicationContext applicationContext) {
        this.serverProperties = serverProperties;
        this.webMvcProperties = webMvcProperties;
        this.applicationContext = applicationContext;
        SpringPropAdapter.springPropAdapter = this;
    }

    public static String getErrorPath(){
        return springPropAdapter.serverProperties.getError().getPath();
    }

    public static String getApplicationId(){
        return springPropAdapter.applicationContext.getId();
    }

    public static String getApplicationName(){
        return springPropAdapter.applicationContext.getApplicationName();
    }

    public static Integer getPort(){
        return springPropAdapter.serverProperties.getPort();
    }

    public static String getContextPath(){
        return springPropAdapter.serverProperties.getServlet().getContextPath();
    }

    /**
     * 获取当前的环境配置
     *
     * @return
     */
    public static String[] getActiveProfiles(){
        return springPropAdapter.applicationContext.getEnvironment().getActiveProfiles();
    }

    /**
     * 获取最后一个环境配置
     *
     * @return
     */
    public static String getLastActiveProfile(){
        String[] profiles = getActiveProfiles();
        return profiles.length != 0 ? profiles[profiles.length-1] : null;
    }

    /**
     * 获取第一个环境配置
     *
     * @return
     */
    public static String getFirstActiveProfile(){
        String[] profiles = getActiveProfiles();
        return profiles.length != 0 ? profiles[0] : null;
    }

    /**
     * 获取默认的环境配置
     *
     * @return
     */
    public static String[] getDefaultProfiles(){
        return springPropAdapter.applicationContext.getEnvironment().getDefaultProfiles();
    }

    /**
     * 获取最后一个默认的环境配置
     *
     * @return
     */
    public static String getLastDefaultProfiles(){
        String[] profiles = getDefaultProfiles();
        return profiles.length != 0 ? profiles[profiles.length-1] : null;
    }

    /**
     * 获取上下文中的属性
     *
     * @return
     */
    public static String getEnvProperty(String key){
        return springPropAdapter.applicationContext.getEnvironment().getProperty(key);
    }
}
